package app.fugema.shop.main.login.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;

import com.base.common.app.AppManager;
import com.base.common.model.bean.QQLoginBean;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.base.BaseActivity;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewModel;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.map.tools.json.JsonUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.LoginActivityBinding;
import app.fugema.shop.helper.AlipayHelper;
import app.fugema.shop.helper.AuthResult;
import app.fugema.shop.helper.WeChatHelper;
import app.fugema.shop.main.login.model.AlipayAuthResult;
import app.fugema.shop.main.login.model.AlipayUserResult;
import app.fugema.shop.main.login.model.MLoginBean;
import app.fugema.shop.main.login.model.MUserInfo;
import app.fugema.shop.main.login.model.OauthInfoBean;
import app.fugema.shop.main.login.model.RegisterResult;
import app.fugema.shop.main.login.vm.LoginVM;
import app.fugema.shop.wxapi.WXEntryActivity;

public class LoginActivity extends BaseActivity<LoginActivityBinding, LoginVM>
{
    private static boolean isRunning = false;

    public static void lunch(Context context) {
        if (!isRunning) {
            context.startActivity(new Intent(context, LoginActivity.class));
            isRunning = true;
        }
    }

    private boolean showPay;

    private enum Item {

        //verification("验证码登录", new LoginVerificationFragment()),
        password("密码登录", new LoginPasswordFragment());

        public String name;
        public BaseFragment fragment;

        Item(String name, BaseFragment fragment) {
            fragment.setTitle(name);
            this.name = name;
            this.fragment = fragment;
        }

    }


    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
    }

    @Override
    protected void initView()
    {

        //接收QQ登录事件
        LiveEventBus.get(AppConstants.QQ_LOGIN, QQLoginBean .class).observe(this, new Observer<QQLoginBean>() {

            @Override
            public void onChanged(QQLoginBean s) {
                qqLogin(s.getOpenid(), s.getAccess_token());
            }
        });

        binding.ivBack.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                finish();
            }
        });
        //!showPay
        if ( true )
        {
            binding.tvTextView1.setVisibility(View.VISIBLE);
            binding.vLine1.setVisibility(View.VISIBLE);
            binding.vLine2.setVisibility(View.VISIBLE);
            binding.givWeChat.setVisibility(View.VISIBLE);
            binding.givQQ.setVisibility(View.VISIBLE);
            binding.tvContent.setVisibility(View.VISIBLE);
        }
        else
        {
            binding.tvTextView1.setVisibility(View.GONE);
            binding.vLine1.setVisibility(View.GONE);
            binding.vLine2.setVisibility(View.GONE);
            binding.givWeChat.setVisibility(View.GONE);
            binding.givQQ.setVisibility(View.GONE);
            binding.tvContent.setVisibility(View.GONE);
        }

        binding.givWeChat.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                //WeChatHelper.login();
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media)
                    {
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map)
                    {
                        LogUtil.e("UMShareAPI", JacksonUtils.transBean2Json( map ));
                        /*
                        {"country":"中国",
                         "unionid":"oQ7Pu580oKMcS2jyVtIbnLLX7TUE",
                         "gender":"男",
                         "city":"",
                         "openid":"oN8gr6FJGzYJ75NHSTpp4PNgNPTs",
                         "language":"zh_CN",
                         "profile_image_url":"https://thirdwx.qlogo.cn/mmopen/vi_32/eeaQ/132",
                         "accessToken":"47_P8-mrv0FSj1to",
                         "access_token":"47_Pj1to",
                         "uid":"oQ7Pu580oKMcS2jyVtIbnLLX7TUE",
                         "province":"湖北",
                         "screen_name":"薯片",
                         "name":"薯片",
                         "iconurl":"https://thirdwx.qlogo.cn/mmopen/vi_32/eemiaQ/132",
                         "expiration":"1627618253666",
                         "expires_in":"1627618253666",
                         "refreshToken":"47_LLVvBCns"}
                            */
                        //成功拿到用户信息
                        String unionid = map.get("unionid");
                        String openid = map.get("openid");
                        String accessToken = map.get("accessToken");
                        String RefreshToken = map.get("refreshToken");
                        String expiration = map.get("expiration");
                        String nickname = map.get("name");
                        String headImg = map.get("profile_image_url");
                        String gender = map.get("gender");
                        int sex = 2;
                        if( gender.contains("男") )
                        {
                            sex = 1;
                        }
                        String province = map.get("province");
                        String city = map.get("city");

                        OauthInfoBean oauthInfoBean = new OauthInfoBean();
                        oauthInfoBean.setOauthType("weixin");
                        oauthInfoBean.setOauthopenId(openid);
                        oauthInfoBean.setUnionid("");
                        oauthInfoBean.setHeadimgurl("");
                        oauthInfoBean.setOauthnickname(nickname);
                        oauthInfoBean.setSex(sex);
                        oauthInfoBean.setProvince( province );
                        oauthInfoBean.setCity(city );
                        //去 第三方登录
                        appLoginByOauth(oauthInfoBean);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable)
                    {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i)
                    {
                        UIUtils.showToastSafes("已取消");
                    }
                });

            }
        });

        binding.givQQ.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                //qqLogin();
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media)
                    {
                    }
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        LogUtil.e("UMShareAPI", JacksonUtils.transBean2Json( map ));
                        /*
                        {"msg":"","ret":"0",
                          "unionid":"",
                          "gender":"男",
                          "is_yellow_vip":"0",
                          "city":"襄阳",
                          "level":"0",
                          "openid":"5C3ED4D52E6C46AC738058CEE2BA0030",
                          "profile_image_url":"http://thirdqq.qlogo.cn/g?b=ois=100&t=1555763805",
                          "accessToken":"EFFC90DD229F7A4FF722CB78A6132BD7",
                          "access_token":"EFFC90DD229F7A4FF722CB78A6132BD7",
                          "uid":"5C3ED4D52E6C46AC738058CEE2BA0030",
                          "is_yellow_year_vip":"0",
                          "province":"湖北",
                          "screen_name":"柠檬",
                          "name":"柠檬",
                          "iconurl":"http://thirdqq.qlogo.cn/g?b=oidibw&s=100&t=1555763805",
                          "yellow_vip_level":"0",
                          "expiration":"1635392244348",
                          "vip":"0","expires_in":"1635392244348"}
                          */
                        //成功拿到用户信息
                        String openid = map.get("openid");
                        String accessToken = map.get("accessToken");
                        String RefreshToken = map.get("RefreshToken");
                        String expiration = map.get("expiration");
                        String nickname = map.get("name");
                        String headImg = map.get("iconurl");
                        String gender = map.get("gender");
                        int sex = 2;
                        if( gender.contains("男") )
                        {
                            sex = 1;
                        }
                        String province = map.get("province");
                        String city = map.get("city");
                        OauthInfoBean oauthInfoBean = new OauthInfoBean();
                        oauthInfoBean.setOauthType("qq");
                        oauthInfoBean.setOauthopenId(openid);
                        oauthInfoBean.setUnionid("");
                        oauthInfoBean.setHeadimgurl("");
                        oauthInfoBean.setOauthnickname(nickname);
                        oauthInfoBean.setSex(sex);
                        oauthInfoBean.setProvince( province );
                        oauthInfoBean.setCity(city );
                        //去 第三方登录
                        appLoginByOauth(oauthInfoBean);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i)
                    {
                        UIUtils.showToastSafes("已取消");
                    }
                });

            }
        });

        binding.givAlipay.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {

                viewModel.getAlipayUser()
                         .observe(LoginActivity.this, new BaseViewObserver<LiveDataWrapper<AlipayAuthResult>>()
                         {
                             @Override
                             protected void onSuccess(LiveDataWrapper<AlipayAuthResult> data)
                             {
                                 LogUtil.e("alipay_auth", data.data.getData() );
                                 AlipayHelper.auth(LoginActivity.this, data.data.getData(), new AlipayHelper.AlipayAuthCallBack()
                                 {
                                     @Override
                                     public void onSucc(AuthResult authResult)
                                     {
                                         //authCode={44518db4f4294633af11b6f8fb65OX09}; resultStatus={9000}; memo={}; result={success=true&result_code=200&app_id=2019062065633602&auth_code=44518db4f4294633af11b6f8fb65OX09&scope=kuaijie&alipay_open_id=20881027473879152640189610915209&user_id=2088502901003097}
                                        //authCode={08fe8d1b6ab54d2b815208568c48PX09}; resultStatus={9000}; memo={}; result={success=true&result_code=200&app_id=2019062065633602&auth_code=08fe8d1b6ab54d2b815208568c48PX09&scope=kuaijie&alipay_open_id=20881027473879152640189610915209&user_id=2088502901003097}
                                         LogUtil.e("alipay_auth_onSucc", authResult.toString() );
                                         String authCode = authResult.getAuthCode();

                                         runOnUiThread( ()->{
                                             viewModel.getAlipayUserByAuth( authCode )
                                                     .observe(LoginActivity.this, new BaseViewObserver<LiveDataWrapper<AlipayUserResult>>() {
                                                         @Override
                                                         protected void onSuccess(LiveDataWrapper<AlipayUserResult> data)
                                                         {
                                                            //{"success":false,"msg":"成功！","Data":{"Address":null,"Area":null,"Avatar":"https://tfs.alipayobjects.com/images/partner/T1KcBoXc4fXXXXXXXX","BusinessScope":null,"CertNo":null,"CertType":null,"City":"襄阳市","CollegeName":null,"CountryCode":null,"Degree":null,"DeliverAddresses":null,"Email":null,"EnrollmentTime":null,"FirmAgentPersonCertExpiryDate":null,"FirmAgentPersonCertNo":null,"FirmAgentPersonCertType":null,"FirmAgentPersonName":null,"FirmLegalPersonCertExpiryDate":null,"FirmLegalPersonCertNo":null,"FirmLegalPersonCertType":null,"FirmLegalPersonName":null,"FirmLegalPersonPictures":null,"FirmPictures":null,"FirmType":null,"Gender":"m","GraduationTime":null,"IsBalanceFrozen":null,"IsCertified":null,"IsStudentCertified":null,"LicenseExpiryDate":null,"LicenseNo":null,"MemberGrade":null,"Mobile":null,"NickName":"亚瑟士","OrganizationCode":null,"PersonBirthday":null,"PersonBirthdayWithoutYear":null,"PersonCertExpiryDate":null,"PersonPictures":null,"Phone":null,"Profession":null,"Province":"湖北省","TaobaoId":null,"UserId":"2088502901003097","UserName":null,"UserStatus":null,"UserType":null,"Zip":null,"Code":"10000","Msg":"Success","SubCode":null,"SubMsg":null,"Body":"{\"alipay_user_info_share_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"avatar\":\"https:\\/\\/tfs.alipayobjects.com\\/images\\/partner\\/T1KcBoXc4fXXXXXXXX\",\"city\":\"襄阳市\",\"gender\":\"m\",\"nick_name\":\"亚瑟士\",\"province\":\"湖北省\",\"user_id\":\"2088502901003097\"},\"sign\":\"iWTLaoA9SkPNQ4/mVWbz3ECpzzmf0n+Q30noCDldwrlkeLjX8wjoHD1BHK2sp5NmurS42i5gwdAyN4WwH6cWrQrEaiSzrhn53kIuwxKHXFnQCTbCVubhul7yWScFPcX4PCBBsAuAL9lXXixI+RJ5ow2PtFo1eE3XikRL1GTXwN1Mt6MurmVUStFTWIyqnDBBb1zn7cmXXByr3auGt7Ck0nhbx1enthAdQKFJwAYdTJeighuUebYTtwmdrDZEwjY0Tw6LWSF1qBsS/O37WTobgeFhSaImVhpHWm+0IVYlZ/xls+ACTt6uqiULlosyfw1Kl9unZWWHrU8hE9X/G0NPMw==\"}","IsError":false}}
                                                            if( UIUtils.isNotEmpty( data.data.getData() ) )
                                                            {

                                                                AlipayUserResult.AlipayShareUser shareUser  = JacksonUtils.getJsonBean(data.data.getData().getBody(),AlipayUserResult.AlipayShareUser.class);
                                                                if( UIUtils.isNotEmpty( shareUser.getAlipay_user_info_share_response() ) )
                                                                {
                                                                    AlipayUserResult.AlipayShareUser.AlipayShareBean shareBean =  shareUser.getAlipay_user_info_share_response();
//成功拿到用户信息
                                                                    String openid = shareBean.getUser_id();
                                                                    String nickname = shareBean.getNick_name();
                                                                    String headImg = shareBean.getAvatar();
                                                                    String gender = shareBean.getGender();
                                                                    int sex = 2;
                                                                    if( gender.contains("m") )
                                                                    {
                                                                        //男
                                                                        sex = 1;
                                                                    }
                                                                    String province = shareBean.getProvince();
                                                                    String city = shareBean.getCity();
                                                                    OauthInfoBean oauthInfoBean = new OauthInfoBean();
                                                                    oauthInfoBean.setOauthType("alipay");
                                                                    oauthInfoBean.setOauthopenId(openid);
                                                                    oauthInfoBean.setUnionid("");
                                                                    oauthInfoBean.setHeadimgurl(headImg);
                                                                    oauthInfoBean.setOauthnickname(nickname);
                                                                    oauthInfoBean.setSex(sex);
                                                                    oauthInfoBean.setProvince( province );
                                                                    oauthInfoBean.setCity(city );
                                                                    //去 第三方登录
                                                                    appLoginByOauth(oauthInfoBean);
                                                                }
                                                            }
                                                         }
                                                     });
                                         } );


                                     }

                                     @Override
                                     public void onFail(String msg)
                                     {
                                         UIUtils.showToastSafes("已取消");
                                         LogUtil.e("alipay_auth_onFail", msg);
                                     }
                                 });
                             }
                         });
            }
        });

        binding.cvpViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return Item.values()[position].name;
            }

            @Override
            public int getCount() {
                return Item.values().length;
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                return Item.values()[position].fragment;
            }
        });


        LiveEventBus.get(AppConstants.LOGIN_PASS, Integer.class).observeSticky(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                setCurrentItem(integer);
            }
        });

        //UIUtils.getString(R.string.app_name)
        SpanUtils.with(binding.tvContent)
                .append("使用信任登录，即表示您已同意商城")
                .append("《用户服务协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds)
                    {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget)
                    {
                        UserAgreementActivity.lunch(getActivity(), true);
                    }
                })
                .append("及")
                .append("《隐私政策》")
                .setClickSpan(new ClickableSpan()
                {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds)
                    {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget)
                    {
//                        UserPrivacyActivity.lunch(getActivity());
                        UserAgreementActivity.lunch(getActivity(), false);
                    }
                })
                .append("有关规定")
                .create();

    }


    /**
     * QQ登录
     */
    public void qqLogin()
    {
        Intent intent = new Intent(this, WXEntryActivity.class);
        intent.putExtra("isQQLogin", true);
        startActivity(intent);
    }


    private void qqLogin(String openid, String accessToken)
    {
        /*
        MutableLiveData<LiveDataWrapper<LoginBean>> qqLogin = viewModel.qqLogin(openid, accessToken);
        qqLogin.observeForever(new BaseViewObserverNew<LiveDataWrapper<LoginBean>>(getActivity()) {
            @Override
            protected void onSuccess(LiveDataWrapper<LoginBean> data) {
                if (UIUtils.isEmpty(data.data.getUser().getMobile())) {
                    UIUtils.showToastSafes("需要绑定手机号码");
                    BindPhoneNumActivity.start(mContext, data.data.getUser().getUserId());
                }
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<LoginBean> data) {
                return UIUtils.isEmpty(data.data.getUser());
            }

            @Override
            protected void onComplete() {
                super.onComplete();
                qqLogin.removeObserver(this);
            }

        });
        */
    }

    //微信登录
    private void loginWeChat(String code) {
        /*
        MutableLiveData<LiveDataWrapper<LoginBean>> wxLogin = viewModel.weChatLogin(code);
        wxLogin.observeForever(new BaseViewObserverNew<LiveDataWrapper<LoginBean>>(getActivity()) {
            @Override
            protected void onComplete() {
                super.onComplete();
                wxLogin.removeObserver(this);
            }

            @Override
            protected void onSuccess(LiveDataWrapper<LoginBean> data) {
                if (UIUtils.isEmpty(data.data.getUser().getMobile())) {
                    UIUtils.showToastSafes("需要绑定手机号码");
                    BindPhoneNumActivity.start(mContext, data.data.getUser().getUserId());
                }
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<LoginBean> data) {
                return UIUtils.isEmpty(data.data.getUser());
            }


        });
        */
    }

    /**
     *  利用第三方信息登录
     */
    private void appLoginByOauth(final OauthInfoBean oauthInfo)
    {
        viewModel.registerUserByUmeng(oauthInfo)
                 .observe(LoginActivity.this, new BaseViewObserver<LiveDataWrapper<MUserInfo>>()
                  {
                        @Override
                        protected void onSuccess(LiveDataWrapper<MUserInfo> data)
                        {
                            if( data.data.isSuccess() )
                            {
                                if( data.data.getCode() == 104 )
                                {
                                    UIUtils.showToastSafesClose( data.data.getMsg() );
                                    //跳转绑定 用户
                                    BindAccountActivity.lunch(LoginActivity.this , oauthInfo);

                                    //LoginActivity.this.finish();
                                }
                                else
                                {
                                    LogUtil.e("第三方登录注册完成 getMUserInfo", JacksonUtils.transBean2Json(data));
                                    UIUtils.showToastSafes("登录成功");
                                    finish();
                                }
                            }
                        }
                  });
    }


    public void setCurrentItem(int index)
    {
        int in = binding.cvpViewPager.getCurrentItem();
        if (in == index) return;
        binding.cvpViewPager.setCurrentItem(index, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRunning = false;
        UMShareAPI.get(this).release();
    }
}
